package com.ireadyit.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * 描述：mybatis配置
 *
 * @author 张延分
 * @date 2021/2/2
 * @return
 **/
@Configuration
@MapperScan("com.ireadyit.mapper")
public class MyBatisConfig {

    @Autowired(required = false)
    private MybatisPlusProperties mybatisPlusProperties;

    @Bean
    @Primary
    @ConfigurationProperties(prefix = Constants.MYBATIS_PLUS)
    public MybatisPlusProperties mybatisPlusProperties() {
        if (mybatisPlusProperties == null) {
            mybatisPlusProperties = new MybatisPlusProperties();
        }
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        // 分布式id
//		dbConfig.setIdType(IdType.ID_WORKER_STR);
        // 开启大写命名
        dbConfig.setCapitalMode(true);
        mybatisPlusProperties.setGlobalConfig(new GlobalConfig().setDbConfig(dbConfig));
        MybatisConfiguration configuration = new MybatisConfiguration();
        // 驼峰命名
        configuration.setMapUnderscoreToCamelCase(true);
        // 对空值的处理
        configuration.setCallSettersOnNulls(true);
        mybatisPlusProperties.setConfiguration(configuration);
        return mybatisPlusProperties;
    }

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,
     * 需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor=new PaginationInnerInterceptor(DbType.MYSQL);
        paginationInnerInterceptor.setMaxLimit(10000L);//查询最多记录条数为10000
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        //官方说，升级mybatis后横向就没有了
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}
